from django.shortcuts import render
from django.http import JsonResponse
from goods.models import GoodsSKU
from django_redis import get_redis_connection
from django.shortcuts import reverse,redirect

# Create your views here.


def CartInfo(request):
    user = request.user
    if not user.is_authenticated:
        return redirect(reverse('df_user/login.html'))

    conn = get_redis_connection('default')
    cart_key = 'cart_%d' % user.id
    cart_dict = conn.hgetall(cart_key)
    sku_list = []
    total_count = 0
    total_price = 0
    try:
        for goods,val in cart_dict.items():
            goods = int(goods)
            sku = GoodsSKU.objects.get(id=goods)
            amount = int(val)*sku.price
            # 动态给sku添加属性
            sku.count = int(val)
            sku.amount = amount
            sku_list.append(sku)
            total_count += int(val)
            total_price += amount
    except Exception as e:
        print(e)
        return JsonResponse({'res': 0, 'errmsg': 'goods is not exist'})

    # print(cart_count)

    return render(request, 'df_cart/cart.html',{'goods':sku_list,
                                                'total_count':total_count,
                                                'total_price':total_price})


def add(request):
    '''商品详情页添加购物车'''
    if request.method == 'POST':
        user = request.user
        if not user.is_authenticated:
            return JsonResponse({'res': 0, 'errmsg': 'please login first'})

        sku_id = request.POST.get('sku_id')
        count = request.POST.get('count')

        if not all([sku_id, count]):
            return JsonResponse({'res':0,'errmsg':'Incomplete information'})

        try:
            count = int(count)
        except:
            return JsonResponse({'res':1,'errmsg':'wrong count'})

        try:
            sku = GoodsSKU.objects.get(id=sku_id)
        except:
            return JsonResponse({'res': 2, 'errmsg': 'goods is not found'})

        conn = get_redis_connection('default')
        cart_key = 'cart_%d'%user.id
        cart_count = conn.hget(cart_key, sku_id)
        if cart_count:
            count += int(cart_count)

        stock = sku.stock
        if count > stock:
            return JsonResponse({'res': 3, 'errmsg': 'count over stock'})
        print(count)
        conn.hset(cart_key, sku_id, count)
        total_count = conn.hlen(cart_key)
        return JsonResponse({'res': 4, 'total_count':total_count,'msg': 'add success'})


def CartUpdate(request):
    '''购物车页面更新数据'''
    if request.method == 'POST':
        user = request.user
        if not user.is_authenticated:
            return JsonResponse({'res': 0, 'errmsg': 'please login first'})

        sku_id = request.POST.get('sku_id')
        count = request.POST.get('count')

        if not all([sku_id, count]):
            return JsonResponse({'res':0,'errmsg':'Incomplete information'})

        try:
            count = int(count)
        except:
            return JsonResponse({'res':1,'errmsg':'wrong count'})

        try:
            sku = GoodsSKU.objects.get(id=sku_id)
        except:
            return JsonResponse({'res': 2, 'errmsg': 'goods is not found'})

        conn = get_redis_connection('default')
        cart_key = 'cart_%d'%user.id
        stock = sku.stock
        if count > stock:
            return JsonResponse({'res': 3, 'errmsg': 'count over stock'})
        print(count)
        conn.hset(cart_key, sku_id, count)
        return JsonResponse({'res': 4, 'total_count':total_count,'msg': 'add success'})